import Taro from '@tarojs/taro'
import configs from '../configuration/index'

function request_good(obj,preobj) {

  let env = Taro.getEnv().toUpperCase()
  let url = obj.url //必填，在此就不做报错提示了
  let method = obj.method || 'GET'
  let data = obj.data || {}
  let header = obj.header || {} //没有s哦
  let identity = obj.identity ? true : false;
  let _wx = env === 'WEAPP' ? true : false
  return Taro.request({
    url, method, data, header,
    dataType: 'json'
  }).then((res) => {
    console.log(url,res.data)
    if(res.data.code === 0){
      return res.data;
    }else {
      if(res.data.code === 1200){
        var token = Taro.getStorageSync('access_token');
        var refresh = Taro.getStorageSync('refresh_token');
        var refreshdata = {
          url : configs.apis.refreshtoken,
          method : 'post',
          data : {refresh_token : refresh},
          header : {'Authorization': 'Bearer '+token},
          identity
        };
        return request_good(refreshdata,obj).then(function (res) {
          console.log('404',res)
          if(res.code === 0){
            if(res.newtoken){
              return res
            }else {
              var token = res.res;
              Taro.setStorageSync('access_token', token.access_token);
              Taro.setStorageSync('refresh_token', token.refresh_token);
              console.log('成功刷新token');
              Taro.hideLoading();
              Taro.stopPullDownRefresh();
              obj.header.Authorization = 'Bearer ' + token.access_token;
              return  request_good(obj);
            }
          }else {
            Taro.showToast({
              title: '账户已过期，请先登录',
              icon: 'none',
              duration: 1000,
            });
            return {};
          }
        })
      }else if(res.data.code === 1201) {
        console.log("token完全失效1",preobj);
        if(_wx){
          return wx_login(preobj).then(res => {
            res.newtoken = true
            return res;
          })
        }else {
          console.log(identity)
          if(!identity){
            Taro.navigateTo({
              url: '/pages/login/login'
            });
          }
          return {};
        }
      }else {
        console.log('throw res', res);   //非认证身份，异常位置
        throw res.data.message ? res.data.message : '服务器异常';
      }
    }
  }).catch((err) => {
    //预防报错
    err = Object.prototype.toString.call(err) == '[object String]' ? err : '请求异常，请稍后再试';
    console.log(err)
    Taro.showToast({
      title: err,
      icon: 'none',
      duration: 1000,
    });
  })
}

//open_id只可能在此设置和删除
function wx_login(next_data,time = 1) { // next_data继续原有请求
 return Taro.getUserInfo().then((obj) => {
    console.log(obj);
   return Taro.login().then((res) =>{
     if (res.code) {
       //发起网络请求
       return Taro.request({
         url: configs.apis['login/wx-xcx'],
         method: 'POST',
         data: {
           js_code: res.code,
           enc_data: obj.encryptedData,
           iv: obj.iv,
           mp_user: 'gh_38770833ee97',
           app_id: 40001081,
           is_onapplaunch: true
         }
       }).then(server_res => {
         var res1 = server_res.data.res
         if(res1){
           console.log('res1',res1,server_res)
           Taro.setStorageSync('access_token', res1.token.access_token)
           Taro.setStorageSync('refresh_token', res1.token.refresh_token)
           Taro.setStorageSync('open_id', res1.open_id)
           if(next_data){
             next_data.header.Authorization = 'Bearer ' + res1.token.access_token;

             return request_good(next_data)

           }else {
             return request_good;
           }
         }else {
           if(time > 1){
             throw "wx-xcx接口获取数据失败!";
           }else{
             return wx_login(next_data,2)
           }

         }
       })
     } else {
       throw "login接口获取数据失败";
     }
   })
  }).catch((err) => {
   Taro.showModal({
     title: '登录失败',
     content: '是否需要重新登陆',
   }).then(res => {
     if(res.confirm){
       wx_login(next_data)
     }else {
       console.log('用户取消了再次登陆')
     }

   })
    console.log('wxlogin,报错提示：',err)
 })
}



export { request_good,wx_login }; //good_request_noverify, good_request,
